<template>
  <div class="content-box">
    <div v-if="rankList.list && rankList.list.length">
      <e-heading :grade="'1'">{{isGroupMatch ? "分组排行榜" : "排行榜"}}</e-heading>
      <!--分组排行榜-->
      <e-sliderbox
        :value="activeGroup"
        :list="groupList"
        :slides="8"
        @change="handleChange"
        style="margin-bottom: 20px;"
        v-if="groupList.length > 0">
        <template slot-scope="scope">
          {{scope.groupName}}组
        </template>
      </e-sliderbox>
      <!--足球-->
      <div v-if="race_detail.matchType==3001">
        <el-table :data="rankList.list" class="rank-table">
          <el-table-column
            prop="chartNo"
            label="排名"
            width="100"
            align="center">
            <template slot-scope="scope">
              <i class="medal gold" v-if="scope.row.chartNo==1" ></i>
              <i v-else-if="scope.row.chartNo==2" class="medal silver"></i>
              <i v-else-if="scope.row.chartNo==3" class="medal bronze"></i>
              <span v-else class="num-rank">
                {{scope.row.chartNo}}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="球队"
            :show-overflow-tooltip="true"
            width="230">
            <template slot-scope="scope">
              <e-img-match class="team-logo" :src="scope.row.iconUrl" />
              <span class="team-name" :title="scope.row.userName">{{scope.row.userName}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="countAll"
            label="场次"
            align="center"
            width="100">
          </el-table-column>

          <el-table-column
            label="胜/平/负"
            align="center"
            width="100">
            <template slot-scope="scope">
                {{scope.row.countWin}} / {{scope.row.countTie}} / {{scope.row.countLost}}
            </template>
          </el-table-column>
          <el-table-column
            label="进/失"
            align="center"
            width="100">
            <template slot-scope="scope">
                {{scope.row.goalIn}}/ {{scope.row.goalLost}}
            </template>
          </el-table-column>
          <el-table-column
            label="净胜"
            align="center"
            width="100">
            <template slot-scope="scope">
              <span v-bind:class="{red:scope.row.difference>0,green:scope.row.difference<0}">
                {{scope.row.goalDifference}}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            prop="point"
            label="积分">
          </el-table-column>
        </el-table>
      </div>
      <!--篮球-->
      <div v-if="race_detail.matchType==3002">
        <el-table :data="rankList.list" class="rank-table">
          <el-table-column
            prop="chartNo "
            label="排名"
            align="center"
            width="100">
            <template slot-scope="scope">
              <i class="medal gold" v-if="scope.row.chartNo ==1" ></i>
              <i v-else-if="scope.row.chartNo ==2" class="medal silver"></i>
              <i v-else-if="scope.row.chartNo ==3" class="medal bronze"></i>
              <span v-else class="num-rank">
                {{scope.row.chartNo }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="球队"
            width="235">
            <template slot-scope="scope">
              <e-img-match class="team-logo" :src="scope.row.iconUrl" />
              <span class="team-name" :title="scope.row.userName">{{scope.row.userName}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="胜/负/胜率"
            align="center"
            width="150">
            <template slot-scope="scope">
                {{scope.row.countWin}} / {{scope.row.countLost}} / {{scope.row.winningPercentage}}%
            </template>
          </el-table-column>
          <el-table-column
            label="得分/失分/分差"
            align="center"
            width="180">
            <template slot-scope="scope">
                {{scope.row.pointAvgWin}} / {{scope.row.pointAvgLost}} / {{scope.row.pointAvgDifference}}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="连胜/连负">
            <template slot-scope="scope">
              <span v-bind:class="{red:scope.row.consecutiveWin>0,green:scope.row.consecutiveWin<0}">
                {{ Math.abs(scope.row.consecutiveWin) }}
                <span v-if="scope.row.consecutiveWin > 0">连胜</span>
                <span v-if="scope.row.consecutiveWin < 0">连负</span>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--网-->
      <div v-if="race_detail.matchType==3004 || race_detail.matchType==300401">
        <el-table :data="rankList.list" class="rank-table" v-bind="getTableProps()">
          <el-table-column
            prop="chartNo"
            label="排名"
            align="center"
            :width="race_detail.isTeam == 1 ? 65 : 100">
            <template slot-scope="scope">
              <i class="medal gold" v-if="scope.row.chartNo==1" ></i>
              <i v-else-if="scope.row.chartNo==2" class="medal silver"></i>
              <i v-else-if="scope.row.chartNo==3" class="medal bronze"></i>
              <span v-else class="num-rank">
                {{scope.row.chartNo}}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="姓名"
            :width="race_detail.isTeam == 1 ? 150 : 235"
            :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <e-avatar class="team-logo" :src="scope.row.iconUrl" />
              <span class="team-name" :title="scope.row.userName" v-if="scope.row.userName2">
                {{scope.row.userName}} & {{scope.row.userName2}}
              </span>
              <span class="team-name" :title="scope.row.userName" v-else>{{scope.row.userName}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="胜/负"
            align="center"
            :width="race_detail.isTeam == 1 ? 90 : 100">
            <template slot-scope="scope">
                {{scope.row.totalWin}} / {{scope.row.totalLost}}
            </template>
          </el-table-column>
          <el-table-column
            label="胜场/负场/净胜场"
            align="center"
            width="150" v-if="race_detail.isTeam == 1">
            <template slot-scope="scope">
                {{scope.row.sceneWin}} / {{scope.row.sceneLost}} / {{scope.row.sceneNet}}
            </template>
          </el-table-column>
          <el-table-column
            label=" 胜盘/负盘/净胜盘"
            align="center"
            width="150">
            <template slot-scope="scope">
                {{scope.row.roundWin}} / {{scope.row.roundLost}} / {{scope.row.roundNet}}
            </template>
          </el-table-column>
          <el-table-column
            label="胜局/负局/净胜局"
            align="center"
            width="150" v-if="race_detail.behalfSmallScore == 1 || race_detail.isTeam == 1">
            <template slot-scope="scope">
              {{scope.row.countWin}} / {{scope.row.countLost}} / {{scope.row.countNet}}
            </template>
          </el-table-column>
          <el-table-column
            prop="point"
            align="center"
            label="积分">
          </el-table-column>
        </el-table>
      </div>
      <!--羽，乒-->
      <div v-if="['3003', '3005'].indexOf( String(race_detail.matchType).substr(0,4)) > -1">
        <el-table :data="rankList.list" class="rank-table"  v-bind="getTableProps()">
          <el-table-column
            prop="chartNo"
            label="排名"
            :width="race_detail.isTeam == 1 ? 65 : 100"
            align="center">
            <template slot-scope="scope">
              <i class="medal gold" v-if="scope.row.chartNo==1" ></i>
              <i v-else-if="scope.row.chartNo==2" class="medal silver"></i>
              <i v-else-if="scope.row.chartNo==3" class="medal bronze"></i>
              <span v-else class="num-rank">
                {{scope.row.chartNo}}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="姓名"
            :width="race_detail.isTeam == 1 ? 150 : 240"
            :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <e-avatar class="team-logo" :src="scope.row.iconUrl" />
              <span class="team-name" :title="scope.row.userName" v-if="scope.row.userName2">
                {{scope.row.userName}} & {{scope.row.userName2}}
              </span>
              <span class="team-name" :title="scope.row.userName" v-else>{{scope.row.userName}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="胜/负"
            align="center"
            :width="race_detail.isTeam == 1 ? 90 : 100">
            <template slot-scope="scope">
                {{scope.row.totalWin}} / {{scope.row.totalLost}}
            </template>
          </el-table-column>
          <el-table-column
            label="胜场/负场/净胜场"
            align="center"
            width="150" v-if="race_detail.isTeam == 1">
            <template slot-scope="scope">
                {{scope.row.sceneWin}} / {{scope.row.sceneLost}} / {{scope.row.sceneNet}}
            </template>
          </el-table-column>
          <el-table-column
            label=" 胜局/负局/净胜局"
            align="center"
            width="150">
            <template slot-scope="scope">
                {{scope.row.countWin}} / {{scope.row.countLost}} / {{scope.row.countNet}}
            </template>
          </el-table-column>
          <el-table-column
            label="得分/失分/净胜分"
            align="center"
            width="150" v-if="race_detail.behalfSmallScore == 1 || race_detail.isTeam == 1">
            <template slot-scope="scope">
              {{scope.row.scoreWin}} / {{scope.row.scoreLost}} / {{scope.row.scoreNet}}
            </template>
          </el-table-column>
          <el-table-column
            prop="point"
            align="center"
            label="积分">
          </el-table-column>
        </el-table>
      </div>
      <!--分页-->
      <el-pagination
        v-bind="getPaginationProps(rankList)"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange">
      </el-pagination>

      <div class="btn-wrapper">
        <el-button type="default" v-if="cRankBtnState" :disabled="cRankBtnDisabled" @click="handleCustomRank" :loading="cRankBtnloading">排名条件自定义</el-button>
        <el-button type="primary" :disabled="!rankList.list" @click="handleExport()">导出Excel</el-button>
      </div>
      <div class="custom-rank-result-wrapper" v-if="CRankData.priorityRule">
        <div class="cr-result-text">{{CRankData.priorityRule.replace(/>/g, ' > ')}}</div>
        <div class="cr-result-dec">
          <h3 class="cr-dec-title">排名规则</h3>
          <div class="cr-dec-content" v-html="CRankData.priorityDesc"></div>
        </div>
      </div>
    </div>
    <e-placeholder v-else text="暂时还没有排行榜哦！"></e-placeholder>
    <!-- 排名条件自定义 弹窗 -->
    <el-dialog class="custom-rank-wrapper" :visible.sync="cRankDialogVisible">
      <div class="c-rank-title">请选择排名条件优先级（请左右拖拽选项改变排序）：</div>
      <div class="c-rank-content">
        <draggable :list="customRankList">
          <el-button class="c-rank-button" type="default" v-for="item in customRankList" :key="item.id">{{item.priorityCh}}</el-button>
        </draggable>
      </div>
      <div class="c-rank-title">您选择的优先级为：</div>
      <div class="c-rank-result">
        <span v-for="(item, index) in customRankList" :key="index">
          {{item.priorityCh}}
          {{index !== customRankList.length - 1 ? '>' : ''}}
        </span>
      </div>
      <div class="c-rank-footer">
        <el-button type="default" @click="handleHideCustomRank">取消</el-button>
        <el-button type="success" @click="handleSaveCustomRank" :loading="crSaveLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from 'api/race'
import ESliderbox from '@e-ui/Sliderbox'
import {mapGetters} from 'vuex'
import {downloadFile, generateGroup, IsCupSeperate} from 'utils'
import { pagingList } from 'utils/mixins'

import draggable from 'vuedraggable'
export default {
  mixins: [pagingList],
  components: {
    ESliderbox,
    draggable
  },
  props: {
    history: { // 列表分页是否产生历史记录
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapGetters({
      race_detail: 'race_detail',
      global: 'global'
    }),
    isGroupMatch () {
      return this.groupMacth.includes(Number(this.$route.query.matchformat))
    },
    IsCupSeperate () {
      return IsCupSeperate(this.race_detail)
    },
    cRankBtnDisabled () {
      /**
       * 排名条件自定义 按钮是否可用
       * 录比分之后不可用
       * 赛事状态为草稿 待审核 审核不通过时不可用（暂不考虑）
       */
      let scoreInputed = this.race_detail.scoreInputed
      scoreInputed = typeof scoreInputed !== 'string' ? scoreInputed : scoreInputed === 'true'
      return scoreInputed
    },
    cRankBtnState () {
      // 是否显示排名条件自定义
      let showCRankList = [3001, 3002] // 暂时只做足球 和 篮球的排名条件处理
      let matchType = this.race_detail.matchType - 0
      return showCRankList.indexOf(matchType) !== -1
    }
  },
  created () {
    /**
     * 排名条件自定义在录比分之后需要刷新状态
     */
    this.$store.dispatch('race_detail', {
      matchId: this.$route.query.id,
      isRun: this.$route.query.isRun,
      matchtype: this.$route.query.matchtype
    })
  },
  mounted () {
    if (this.isGroupMatch || this.IsCupSeperate) { // 是否是杯赛
      this.query.groupType = 1
    } else {
      this.query.groupType = 0
    }
  },
  data () {
    return {
      groupMacth: [24012, 24013, 24014, 24015, 24016],
      rankList: [],
      query: this.getQuery({
        matchId: this.$route.query.id
      }),
      groupList: [],
      activeGroup: {},
      groupCount: 0,
      customRankList: [],
      // cRankButtonState
      CRankData: {}, // 排序结果
      crSaveLoading: false,
      cRankBtnloading: false,
      cRankDialogVisible: false // 报名条件自定义弹窗状态
      // doubleType: [20006, 20008, 20010] // 双人类型赛事
      // teamType: [20002, 20004, 20013, 20015, 20016, 20017] // 团体类型赛事
    }
  },
  watch: {
    '$route': 'getDataList'
  },
  methods: {
    getDataList (query) {
      let matchType = this.$route.query.matchtype.substr(0, 4) // 赛事类型
      api.getChart(query).then((res) => {
        if (this.groupList.length === 0) { // 首次执行分组
          this.groupList = generateGroup(res.data.groupCount)
        }
        this.activeGroup = this.groupList[this.query.groupType - 1]
        if (matchType === '3001') { // 3001(足球)
          this.rankList = res.data.footballPage
        } else if (matchType === '3002') { // 3002(篮球)
          this.rankList = res.data.basketballPage
        } else if (matchType === '3003') { // 3003(羽毛球)
          this.rankList = res.data.badmintonPage
        } else if (matchType === '3004') { // 3004(网球)
          this.rankList = res.data.tennisPage
        } else if (matchType === '3005') { // 3005(乒乓球)
          this.rankList = res.data.pingpongPage
        }
        this.CRankData = {
          priorityDesc: res.data.priorityDesc,
          priorityRule: res.data.priorityRule
        }
      })
    },
    fetch (query) {
      query.page = query.page || 1
      query.rows = query.rows || 50
      this.getDataList(query)
    },
    // 下载积分榜Excel
    handleExport () {
      let matchType = this.$route.query.matchtype // 赛事类型
      // var prefix = '/api/match/sign/exprot'
      let url = '/api/match/export/matchChartInfo?matchId=' + this.$route.query.id + '&behalfSmallScore=' + this.race_detail.behalfSmallScore + '&isTeam=' + this.race_detail.isTeam
      let fileName = ''
      switch (matchType) {
        case '3001':
          fileName = '足球联赛'
          break
        case '3002':
          fileName = '篮球联赛'
          break
        case '3003':
          fileName = '羽毛球联赛'
          break
        case '3004':
          fileName = '网球联赛'
          break
        case '3005':
          fileName = '乒乓球联赛'
          break
        case '300401':
          fileName = '网球团体'
          break
        case '300501':
          fileName = '乒乓球团体'
          break
        case '300301':
          fileName = '羽毛球团体'
          break
      }
      var _this = this
      downloadFile(url, fileName + '.xlsx', function (blob) {
        _this.$message({
          message: '下载出错，请稍后再试',
          type: 'warning'
        })
      })
    },
    handleChange (val) { // 分组积分榜
      this.activeGroup = val
      this.query.groupType = this.activeGroup.id + 1
      this.fetch(this.query)
    },
    handleCustomRank () {
      this.cRankBtnloading = true
      api.getRankPriority({matchId: this.race_detail.id}).then(({ data }) => {
        let resultArr = []
        let listItem = data.listItem
        let sortArr = data.arryNumber || []
        if (sortArr.length) {
          let tempArr = sortArr.map(item => {
            return listItem.find(k => k.id - 0 === item - 0)
          })
          // 如果长度不等 说明解析有问题 则不做处理 直接赋默认值
          resultArr = tempArr.length === listItem.length ? tempArr : listItem
        } else {
          resultArr = listItem
        }
        this.customRankList = resultArr
        this.cRankDialogVisible = true
      }).finally(() => {
        // 成功失败都会执行
        this.cRankBtnloading = false
      })
    },
    handleSaveCustomRank () {
      let subData = {}
      subData.matchId = this.race_detail.id
      subData.arryNumber = this.customRankList.map(k => k.id)
      this.crSaveLoading = true
      api.saveRankPriority(subData).then(({ data }) => {
        this.CRankData.priorityDesc = data.priorityDesc
        this.CRankData.priorityRule = data.priorityRule
        this.handleHideCustomRank()
      }).finally(() => {
        // 成功失败都会执行
        this.crSaveLoading = false
      })
    },
    handleHideCustomRank () {
      this.cRankDialogVisible = false
      this.customRankList = []
    }
  }
}
</script>

<style lang="scss" scoped>
  
  .team-logo{
    width: 32px;
    height:32px;
    display: inline-block;
    margin-right: 5px;
    border-radius: 50%;
  }
  .num-rank{
    width: 26px;
    height: 26px;
    color: #fff;
    font-size: 12px;
    line-height: 26px;
    background: #ccc;
    display: inline-block;
    text-align: center;
    border-radius: 3px;
  }
  .rank-table{
    .medal{
      display: inline-block;
      width:32px;
      height: 32px;
      &.gold{
        background: url('/static/images/rank/gold.svg')
      }
      &.silver{
        background: url('/static/images/rank/silver.svg')
      }
      &.bronze{
        background: url('/static/images/rank/bronze.svg')
      }
    }
    .red{
      color:$color-error;
    }
    .green{
      color:$color-primary;
    }
  }
  .btn-wrapper{
    text-align: center;
    margin-top: 30px;
  }

  .team-name{
    line-height:40px;
  }
  .custom-rank-wrapper{
    .c-rank-content{
      padding-top: 35px;
      padding-bottom: 70px;
      .c-rank-button{
        &:hover{
          border-color: $color-warning;
          background-color: $color-warning;
          color: #fff;
        }
      }
    }
    .c-rank-result{
      padding: 20px 0 35px;
      text-align: center;
      font-weight: 700;
    }
    .c-rank-footer{
      text-align: center;
    }
  }
  .custom-rank-result-wrapper{
    margin-top: 125px;
    .cr-result-text{
      font-size: 16px;
      font-weight: 700;
    }
    .cr-result-dec{
      color: $color-black-base;
      margin-top: 25px;
      .cr-dec-title{
        font-weight: normal;
        font-size: 16px;
      }
      .cr-dec-content{
        line-height: 38px;
        p{
          padding: 0;
          margin: 0;
        }
      }
    }
  }
</style>
<style lang="scss">
.rank-table table tr td{
  height: 60px;
  line-height: 60px;
  font-size: 12px;
}
.custom-rank-wrapper{
  .el-dialog{
    width: 500px;
    .el-dialog__body{
      padding-top: 8px;
    }
  }
}
</style>
